﻿/**
TODO: SessionID or RoomID
Pass the session id to server..
**/

define([
    "jQuery",
	"jQuery-ui",
	"dtpicker",
   
	], function ($,$ui,dtpicker) {
	
    return {
		baseUrl:document.getElementById("base_url").value,
		fileId:document.getElementById("file_id").value,
		pageId:document.getElementById("page_id").value,
		historyContent:false,
		currentStackIndex:-1,
		isAutoPlay:false,
		autoPlayTimeout:false,
		
		pan : function(){
			
		},

        init: function () {
			var locale=$("#app_lang").val();
			var dtPickerLocale="en";
			if(locale == "english")
			{
				String.locale = "en";
			}
			else if(locale == "japanese")
			{
				String.locale = "jp";
				dtPickerLocale="ja";
			}
			$("#date-picker").val('');
			var currentDate = new Date();
			$('#date-picker').appendDtpicker({
				'minuteInterval' : 15,
				'current' : currentDate.getFullYear()+'-'+(currentDate.getMonth()+1)+'-'+currentDate.getDate()+' 09:00',
				'locale':"en"
			});
			var url = App.baseUrl+"CommHub/get_history";
			var data = {
				"p_id":  App.pageId,
				"f_id":  App.fileId
			};
			var request=$.ajax({
				type: 'GET',
				url: url,
				data:data,
			});	
			request.done(function(msg) {
				console.log(msg);
				App.historyContent = JSON.parse(msg);
			});
			request.fail(function(jqXHR, textStatus) {
				
			
			});
			request.always(function(){
				$("#overlay").hide();
			});
			$(".history_cells").on('click',function(){
				var selectedNum = $(this).attr('data-history');
				selectedNum = parseInt(selectedNum);
				
				App.reset();
				while(App.currentStackIndex != selectedNum)
				{
					if(App.currentStackIndex > selectedNum)
						App.prev();
					else
						App.next();
				}
			});
                                         
		},
		toggle_visibility:function(id){
			$('#'+id).toggle();
		},
		
		localize : function (string, fallback) {
			var localized = string.toLocaleString();
			if (localized !== string) {
				return localized;
			} else {
				return fallback;
			}
		},
		
		
		loadTextObject:function(data){
			
			var style = "";
			var color = "";
			if(data.object_type == "buble"){
				if(data.kind){
					if(data.kind == "bubble1"){
						style = 'class="triangle-border"';
					}else if(data.kind == "bubble2"){
						style = 'class="triangle-border right"';
					}else if(data.kind == "bubble3"){
						style = 'class="triangle-border top"';
					}else if(data.kind == "bubble4"){
						style = 'class="triangle-border left"';
					}else if(data.kind == "bubble5"){
						style = 'class="triangle-border right"';
					}else{
						style = 'class="triangle-border"';
					}
				}else{
					style = 'class="triangle-border"';
				}
			}else if(data.object_type == "sticky-text"){
				style = 'class="sticky taped"';
				color = '#F4F39E';
				if(data.kind){
					if(data.kind == "sticky2"){
						color = '#d6f0fa';
					}else if(data.kind == "sticky3"){
						color = '#f5d1f5';
					}else if(data.kind == "sticky4"){
						color = '#cffdc9';
					}else if(data.kind == "sticky5"){
						color = '#d5cdfe';
					}
				}
			}
			
			var newTextObject =  $('<div ' + style + '></div>')
									.attr("id",data.id)
									.attr("object_type",data.object_type)
									.addClass("nic-edit-element").appendTo($('#rootContainer'));
			if(data.object_type == "sticky-text")
			{
				newTextObject.css("background-color",color);
			}
								
			newTextObject.css("left",(parseInt(data.posx)));
			newTextObject.css("top",(parseInt(data.posy)));
			newTextObject.css("height",parseInt(data.height));
			newTextObject.css("width",parseInt(data.width));
			newTextObject.css("overflow","visible");
			newTextObject.attr("kind",data.kind);
			
			newTextObject.html("<div id='text_content_"+data.id+"' style='overflow:hidden;width:100%;height:100%;'>" + data.content + "</div>");
			$("#"+data.id).css("position", "");
			console.log(newTextObject);
		},
		
		loadStickyTextObject:function(data){
			var newStickyTextObject =  $('<div></div>')
									.attr("id",data.id)
									.attr("object_type",data.object_type)
									.addClass("nic-sticky-edit-element").appendTo($('#rootContainer'));
			newStickyTextObject.css("left",(parseInt(data.posx)));
			newStickyTextObject.css("top",(parseInt(data.posy)));
			newStickyTextObject.css("height",parseInt(data.height));
			newStickyTextObject.css("width",parseInt(data.width));
			newStickyTextObject.css("background-color",data.background);
			newStickyTextObject.css("background",data.background);
			newStickyTextObject.css("overflow","visible");
			newStickyTextObject.html("<div id='text_content_"+data.id+"' style='overflow:hidden;width:100%;height:100%;'>" + data.content + "</div>");
			$("#"+data.id).css("position", "");
		},
		loadDrawingObject : function(data){  
			//console.log(data);
			var newImgContainer = $('<div></div>').attr({'id':data.id,'class':'image', 'type':data.type, 'object_type':data.type, 'created_by':data.created_by, 'created_date':data.created_date}).appendTo($('#rootContainer'));
			newImgContainer.css("position","absolute");
			newImgContainer.css("left",(parseInt(data.posx)));
			newImgContainer.css("top",(parseInt(data.posy)));
			newImgContainer.css("height",parseInt(data.height));
			newImgContainer.css("width",parseInt(data.width));
			newImgContainer.css("overflow","visible");
		
			var newImgComponent = $('<img></img>').attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id}).appendTo(newImgContainer);
			newImgComponent.attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id});
		},
		
		loadTableObject:function(data){
		
		var newTableContainer = $('<div></div>')
			.attr({'id':data.id,'class':'table','type':data.type, 'object_type':data.object_type, 'border_style':data.border_style})
			.attr("bd-style",data.style)
			.attr("thickness",data.thickness)
			.css("overflow","visible")
			.css("cursor", 'default')
			.css("border", '1px solid rgb(160, 160, 164)')
			.css("position","absolute")  
			.css("z-index","18")
			.css("left",(parseInt(data.posx)))
			.css("top",(parseInt(data.posy)))
			.css("height", (parseInt(data.height)))
			.css("width", (parseInt(data.width)))
			.appendTo($('#rootContainer'));
			
			newTableContainer.css("cursor", 'default');
			
			
			var tableConteiner = $('<table></table>')
			.attr({ id: "tbl_"+data.id, border:"2px", width:"100%", height:"100%"})
			.html(data.content_table)
			.css('border',data.border_style)
			.appendTo(newTableContainer);
		},
		
		loadChartObject : function(data){
		
			var newChartContainer = $('<div></div>').attr({'id':data.id,'class':'image','type':data.type, 'object_type':data.object_type, 'chart-data':data.data_chart}).appendTo($('#rootContainer'));
			newChartContainer.css("position","absolute");
			newChartContainer.css("left",(parseInt(data.posx)));
			newChartContainer.css("top",(parseInt(data.posy)));
			newChartContainer.css("height",parseInt(data.height));
			newChartContainer.css("width",parseInt(data.width));
			newChartContainer.css("overflow","visible");
			var newChartImgContainer = $('<img></img>').attr({ 'src': App.baseUrl+data.image_url,'id':"img"+data.id}).appendTo(newChartContainer);
			
		},
		loadSingleObject:function(content){
			var loadedObject = content;
			// console.log(loadedObject);
			if(loadedObject.operation == "ADD")
			{
				console.log("adding");
				if(loadedObject.type=="image")
					App.loadDrawingObject(loadedObject.previous_content);
				if(loadedObject.type=="attach")
					App.loadDrawingObject(loadedObject.previous_content);
				if(loadedObject.type=="text" || loadedObject.type=="buble" || loadedObject.type=="sticky-text")
					App.loadTextObject(loadedObject.previous_content);
				if(loadedObject.type=="chart")
					App.loadChartObject(loadedObject.previous_content);
				// if(loadedObject.type=="sticky-text")
					// App.loadStickyTextObject(loadedObject.previous_content);
				if(loadedObject.type=="table")
					App.loadTableObject(loadedObject.previous_content);
			}
			else if(loadedObject.operation == "EDIT")
			{
				console.log("editing");
				App.updateSingleObject(loadedObject.changed_content);
			}
			else if(loadedObject.operation == "DEL")
			{
				console.log("deleting");
				// App.deleteSingleObject(loadedObject.previous_content);
				App.deleteSingleObject(loadedObject);
			}
		},
		loadSSingleObject:function(content){
			var loadedObject = content;
			console.log(loadedObject);
			if(loadedObject.operation == "ADD")
			{
				if(loadedObject.type=="image")
					App.loadDrawingObject(loadedObject.previous_content);
				if(loadedObject.type=="attach")
					App.loadDrawingObject(loadedObject.previous_content);
				if(loadedObject.type=="text" || loadedObject.type=="buble" || loadedObject.type=="sticky-text")
					App.loadTextObject(loadedObject.previous_content);
				if(loadedObject.type=="chart")
					App.loadChartObject(loadedObject.previous_content);
				// if(loadedObject.type=="sticky-text")
					// App.loadStickyTextObject(loadedObject.previous_content);
				if(loadedObject.type=="table")
					App.loadTableObject(loadedObject.previous_content);
			}
			else if(loadedObject.operation == "EDIT")
			{
				App.updateSingleObject(loadedObject.changed_content);
			}
			else if(loadedObject.operation == "DEL")
			{
				// App.deleteSingleObject(loadedObject.previous_content);
				App.deleteSingleObject(loadedObject);
			}
		},
		deleteSingleObject:function(content)
		{
			var deletedObject = content;
			console.log("Deleting");
			// console.log(deletedObject);
			$('#'+deletedObject.changed_object_id).remove();
		},
		updateSingleObject:function(content)
		{
			var existingObject=false;	
			if(content.type=="background" )
			{
			
				$('#rootContainer').css('background-image', 'url(' + App.baseUrl+content.image_path+'?ts='+(new Date).getTime()+' )');
				$('#rootContainer').css('background-size', '100%');
				return;
			}
			$('#rootContainer').children().each(function(){
				if($(this).attr('id') == content.id)
				{
					existingObject=$(this);
				}
			});
			if(existingObject)
			{
				if(content.posx != -1 && content.posy != -1 )
				{
					existingObject.css('left',parseInt(content.posx));
					existingObject.css('top',parseInt(content.posy));
				}
				
				if(content.width != -1&& content.height != -1 )
				{
					existingObject.css('width',parseInt(content.width));
					existingObject.css('height',parseInt(content.height));
				}
				
				if(content.type=="image" || content.type=="chart")
				{
					var newImage_url = App.baseUrl+content.image_url;
				
					if(typeof content.image_url != "undefined" && newImage_url != $("#img"+existingObject.attr('id')).attr("src"))
					{
						
						 $("#img"+existingObject.attr('id')).attr("src",newImage_url);
					}
				}
				else if(content.type=="text" || content.type=="buble" ||  content.type=="sticky-text" )
				{
						console.log("content");
						console.log(content);
						console.log($("#text_content_"+existingObject.attr('id')).html());
						if(content.content != $("#text_content_"+existingObject.attr('id')).html())
						{
							 $("#text_content_"+existingObject.attr('id')).html(content.content);
						}
						if(content.type=="sticky-text")
						{
							$("#"+existingObject.attr('id')).css('background',content.background);
							$("#"+existingObject.attr('id')).css('background-color',content.background);
						}
				}
			}
		},
		next:function(){
			if(App.currentStackIndex+1 >= App.historyContent.length)
			{
				return;
			}
			$("#history_"+App.currentStackIndex).css("background-color","white");
			App.currentStackIndex++;
			$("#history_"+App.currentStackIndex).css("background-color","yellow");
			
			console.log("next "+App.currentStackIndex);
			var currentState = App.historyContent[App.currentStackIndex];
			console.log(currentState);
			App.loadSingleObject(currentState);
 
		},
		prev:function(){
			if(App.currentStackIndex <= 0)
			{
				App.reset();
				return;
			}
			
			var previousState = App.historyContent[App.currentStackIndex];
			$("#history_"+App.currentStackIndex).css("background-color","white");
			App.currentStackIndex--;
			$("#history_"+App.currentStackIndex).css("background-color","yellow");
			
			console.log("prev "+App.currentStackIndex);
			var currentState = App.historyContent[App.currentStackIndex];
			
			if(currentState.operation == "ADD")
				App.updateSingleObject(currentState.changed_content);
			else if(currentState.operation == "DEL")
				// App.deleteSingleObject(currentState.previous_content);
				App.deleteSingleObject(currentState);
			else
				App.loadSingleObject(currentState);

			//find previous state,and do the opposite.
			if(previousState.operation == "ADD")
			{
				// App.deleteSingleObject(previousState.changed_content);
				App.deleteSingleObject(previousState);
			}
			else if(previousState.operation == "DEL")
			{ 
				var contentCopy = jQuery.extend(true, {}, previousState);
				contentCopy.operation="ADD";
				App.loadSingleObject(contentCopy);
				
			}
		},
		autoPlay:function(){
			if(App.isAutoPlay)
				return;
				console.log("start autoplay");
			App.isAutoPlay=true;
			App.autoPlayTimeout = setInterval(function() {App.next();}, 2000);
		},
		stopAutoPlay:function(){
			if(!App.isAutoPlay)
				return;
				console.log("stop autoplay");
			App.isAutoPlay=false; 
			clearInterval(App.autoPlayTimeout);
		},
		reset:function(){
			console.log("Resetting");
			App.stopAutoPlay();
			$("#history_"+App.currentStackIndex).css("background-color","white");
			App.isAutoPlay=false;
			App.currentStackIndex=-1;
			$('#rootContainer').children().each(function(){
				$(this).remove();
			});
		},
		minimize:function(){
			console.log("minimize");
			$('#page_thumbnails').hide();
			$('#maximize_button').show();
		},
		maximize:function(){
			console.log("maximize");
			$('#page_thumbnails').show();
			$('#maximize_button').hide();
		},
		jumpToDate:function(){
			if(App.historyContent.length <= 0)
				return;
			var dateValue = $('#date-picker').val();
			//validate input
			var splitDateTime = dateValue.split(' ');
			if(splitDateTime.length != 2)
			{
				alert(App.localize("%invalid_date"));
				return;
			}			
			var date = splitDateTime[0];
			var time = splitDateTime[1];
			
			//parse itime
			time = time.split(':');
			if(time.length != 2)
			{
				alert(App.localize("%invalid_date"));
				return;
			}			
			var hour = time[0];
			var minute = time[1];
			hour = parseInt(hour);
			minute = parseInt(minute);
			if(hour > 23 || hour <0 || isNaN(hour))
			{
				alert(App.localize("%invalid_date"));
				return;
			}
			if(minute > 60 || minute <0 || isNaN(minute))
			{
				alert(App.localize("%invalid_date"));
				return;
			}
			//parse date
			date = date.split('-');
			if(date.length != 3)
			{
				alert(App.localize("%invalid_date"));
				return;
			}	
			var year = date[0];
			var month = date[1];
			var day = date[2];
			year = parseInt(year);
			month = parseInt(month);
			day = parseInt(day);
			
			if(year <0 || isNaN(year))
			{
				alert(App.localize("%invalid_date"));
				return;
			}
			if(month > 12 || month <0 || isNaN(month))
			{
				alert(App.localize("%invalid_date"));
				return;
			}	
			month-=1;
			if(day > 31 || day <0 || isNaN(day))
			{
				alert(App.localize("%invalid_date"));
				return;
			}		
			App.reset();
			dateValue =  Date.UTC(year,month,day,hour,minute,0,0);	
			dateValue=dateValue/1000;
			var d = new Date;
			dateValue += (d.getTimezoneOffset() * 60);
		
		
			var breakPoint=0;
			for(var i  = 0;i<App.historyContent.length;i++){
				var currentState = App.historyContent[i];
				
				var currentDate =parseInt($("#h_id_"+currentState.history_id).val());
				console.log(currentDate+"/"+dateValue);
				breakPoint = i;
				if(currentDate > dateValue)
				{
					break;
				}
			}
			// var el = document.getElementById("history_"+breakPoint);
			// el.scrollIntoView(true);
			while(App.currentStackIndex != breakPoint)
			{
				if(App.currentStackIndex > breakPoint)
					App.prev();
				else
					App.next();
			}
		}
	
	
	}
});